<template>
    <div class="list-item">
        <div class="item-box clearfix">
            <div class="col col-checked">
                <i :class="{active:goodInfo.checked}" @click="updateCheck">√</i>
            </div>
            <div class="col col-img">
                <img v-lazy="goodInfo.picture" />
            </div>
            <div class="col col-name">{{ goodInfo.goodsName }}</div>
            <div class="col col-price">{{ Number(goodInfo.unitPrice).toFixed(2) }} 元</div>
            <div class="col col-num">
                <div class="num-box">
                    <a @click="handler('minus',-1,goodInfo.goodsId)">-</a>
                    <!-- 双重转换值，保证一定是整数 -->
                    <input type="text" :value="goodInfo.number" @change="handler('change',Number.parseInt(Number($event.target.value)),goodInfo.goodsId)" ref="numBox" />
                    <a @click="handler('add',1,goodInfo.goodsId)">+</a>
                </div>
            </div>
            <div class="col col-total">{{ Number(goodInfo.price).toFixed(2) }} 元</div>
            <div class="col col-action">
                <a @click="deleteCart">×</a>
            </div>
        </div>
        <div class="mask" v-show="goodInfo.isSell != 1">
            <p>该商品已下架</p>
        </div>
    </div>
</template>

<script>
import { throttle } from "lodash-es";
export default {
    name: "list-item",
    data() {
        return {};
    },
    methods: {
        // 让子组件来利用store发起请求
        // 通过throttle的节流来限制其点击次数，避免频繁向服务器发送请求
        updateCheck: throttle(async function updateCheck() {
            let params = {
                goodId: this.goodInfo.goodsId,
                checked: this.goodInfo.checked ? 0 : 1,
            };
            try {
                await this.$store.dispatch("shopcart/updateChecked", params);
                this.$emit("update");
            } catch (error) {
                this.$message({
                    message: error,
                    type: "error",
                });
            }
        }, 500),

        handler: throttle(async function handler(type, disNums, goodsId) {
            // 判断类型
            switch (type) {
                case "minus":
                    // 如果商品数量小于1，就发出警告
                    // 注意，逻辑非的优先级要大于（< or >）两个比较符号，要用括号括起来
                    if (!(this.goodInfo.number > 1)) {
                        disNums = 0;
                        this.$message({
                            message: "商品数量不能小于1",
                            type: "warning",
                        });
                    }
                    break;

                case "add":
                    // 如果商品数量此时要大于前端的客户量，应当自动将其变为最大库存
                    if (!(this.goodInfo.number < this.goodInfo.inventory)) {
                        disNums =
                            this.goodInfo.inventory - this.goodInfo.number;
                        this.$message({
                            message: "商品数量超过库存，即将为您选择最大值",
                            type: "warning",
                        });
                    }
                    break;

                case "change":
                    // 判断是否是NaN,是的话终止函数，让他变为一开始的数值
                    if (!(disNums === disNums)) {
                        this.$refs.numBox.value = this.goodInfo.number;
                        this.$message({
                            message: "请不要填写非数字内容！",
                            type: "error",
                        });
                        return;
                    }
                    // 判断是否超出范围
                    if (disNums < 1 || disNums > this.goodInfo.inventory) {
                        // 如果超过范围，把商品数量设置为最大或者最小
                        disNums =
                            disNums < 1
                                ? 1 - this.goodInfo.number
                                : this.goodInfo.inventory -
                                  this.goodInfo.number;
                        this.$message.warning("超出范围，即将为您设定边界值");
                    } else {
                        // 未超出则设定值为差值
                        disNums = disNums - this.goodInfo.number;
                    }
                    break;
            }
            // 发起请求
            let params = {
                goodId: goodsId,
                editNums: disNums,
            };
            // 用Promise来进行异步操作
            let resultPromise = new Promise((resolve, reject) => {
                // 用嵌套Promise，实在是完美
                let result = Promise.resolve(
                    this.$store.dispatch("shopcart/editShopCartNums", params)
                );
                result.then(resolve, reject);
            });

            resultPromise.then(
                (val) => {
                    this.$emit("update");
                },
                (error) => {
                    this.$message.error(error);
                }
            );
        }, 600),

        async deleteCart() {
            try {
                await this.$store.dispatch(
                    "shopcart/deleteShopCartGoods",
                    this.goodInfo.goodsId
                );
                this.$emit("update");
                this.$message.success("删除成功！");
            } catch (error) {
                this.$message.error(error);
            }
        },
    },
    props: ["goodInfo"],
};
</script>

<style lang="less" scoped>
.list-item {
    position: relative;
    .item-box {
        padding: 15px 0;
        .col {
            line-height: 80px;
            height: 80px;
            font-size: 16px;
        }

        .col-checked {
            width: 110px;
            i {
                display: inline-block;
                text-align: center;
                border: 1px solid rgb(224, 224, 224);
                color: white;
                width: 18px;
                height: 18px;
                line-height: 18px;
                margin-left: 24px;
                margin-right: 15px;
                font-style: normal;
                font-size: 14px;
                font-weight: bold;
                cursor: pointer;
                user-select: none;
            }

            i:hover {
                color: #424242;
            }

            .active {
                background-color: rgb(255, 106, 0);
                color: white !important;
            }
        }
        .col-name {
            font-size: 18px;
        }

        .col-num {
            .num-box {
                border: 1px solid rgb(224, 224, 224);
                height: 38px;
                line-height: 38px;
                margin-top: 21px;
                display: flex;

                input[type="text"] {
                    width: 74px;
                    height: 38px;
                    text-align: center;
                    border: none;
                    padding: 0;
                    outline: none;
                    font-size: 16px;
                    font: inherit;
                }

                a {
                    width: 38px;
                    height: 38px;
                    text-align: center;
                    font-size: 19px;
                    font-weight: bold;
                    cursor: pointer;
                    transition: background-color 0.3s ease;
                    user-select: none;
                }

                a:hover {
                    background-color: rgb(224, 224, 224);
                }
            }
        }

        .col-total {
            color: #ff6700;
        }

        .col-action {
            position: relative;
            a {
                height: 24px;
                width: 24px;
                display: block;
                line-height: 23px;
                font-size: 20px;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                border-radius: 50%;
                transition: all 0.3s ease;
                cursor: pointer;
                user-select: none;
            }

            a:hover {
                background-color: rgb(91, 81, 69);
                color: white;
            }
        }
    }

    .col {
        white-space: nowrap;
        color: #424242;
        float: left;
    }
    .col-img {
        width: 120px;
        img {
            width: 80px;
        }
    }
    .col-name {
        width: 380px;
        padding-left: 40px;
    }

    .col-price {
        width: 140px;
        text-align: center;
    }

    .col-num {
        width: 150px;
        text-align: center;
    }

    .col-total {
        width: 120px;
        text-align: center;
    }

    .col-action {
        width: 130px;
        text-align: center;
    }

    .mask {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.3);
        // 不知道为什么会失效，但是自己开一个html文件不会失效
        // display: table-cell;
        // vertical-align: middle;
        text-align: center;

        p {
            line-height: 110px;
            user-select: none;
        }
    }
}
</style>